package com.innazis.jfrogsurvey;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.innazis.jfrogsurvey.backendmanager.ModelManager;
import com.innazis.jfrogsurvey.backendmanager.ModelManagerListener;
import com.innazis.jfrogsurvey.backendmanager.ParserUtility;
import com.innazis.jfrogsurvey.config.Constants;
import com.innazis.jfrogsurvey.managers.SurveyManager;
import com.innazis.jfrogsurvey.obj.AnswerObj;
import com.innazis.jfrogsurvey.obj.QuestionObj;
import com.innazis.jfrogsurvey.obj.ServerResponse;
import com.innazis.jfrogsurvey.obj.SurveyObj;
import com.innazis.jfrogsurvey.utility.DialogUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Inna on 14.06.14.
 */
public class SurveyActivity extends BaseActivity {

    private Bundle extras;
    LinearLayout ll;
	ScrollView sv;
	Button btnSubmit;
    Button btnDelete;
	TextView tvSurveyName;
	TextView tvSurveyTitle;
    TextView tvUserData;
    View line_survey;
    View line_user;
	SurveyManager sManager;
	SurveyObj currentSurvey;
	protected SurveyActivity self;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		self = this;
		initUI();
	}

	private void initUI() {
		sv = new ScrollView(self);
		ll = new LinearLayout(self);
		ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);

        line_survey = new View(this);
        line_survey = (View)getLayoutInflater().inflate(R.layout.separator_template, null);
        line_user = new View(this);
        line_user = (View)getLayoutInflater().inflate(R.layout.separator_template, null);

		sManager = new SurveyManager(self);
		extras = getIntent().getExtras();
		if (extras != null) {
			String user_data = extras.getString(Constants.user_data_p);
            // check if a survey was filled by this user (user_data)
            int survey_id = sManager.surveyVerification(Constants.user_data_p, user_data, Constants.TBL_SURVEYS);

			currentSurvey = (survey_id > 0) ? sManager.getSurvey(survey_id) : sManager.copySurvey(user_data);
			tvSurveyName = new TextView(self);
            tvSurveyName = (TextView)getLayoutInflater().inflate(R.layout.tv_name_template, null);
			tvSurveyName.setText(currentSurvey.get_survey_name());
			ll.addView(tvSurveyName);
			tvSurveyTitle = new TextView(self);
            tvSurveyTitle = (TextView)getLayoutInflater().inflate(R.layout.tv_name_template, null);
			ll.addView(tvSurveyTitle);
            ll.addView(line_survey);
			tvSurveyTitle.setText(currentSurvey.get_survey_title());
            tvUserData = new TextView(self);
            tvUserData.setText("QR/Barcode: " + currentSurvey.get_user_data());
            ll.addView(tvUserData);
            ll.addView(line_user);
			for (QuestionObj questionObj : currentSurvey.get_questions_list()) {
				createQuestionView(questionObj);
			}
            btnSubmit = new Button(this);
            btnSubmit = (Button)getLayoutInflater().inflate(R.layout.btn_submit_template, null);
            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (saveResults()) {
                        Intent i = new Intent(self, MainActivity.class);
                        startActivity(i);
                    }
                }
            });

            ll.addView(btnSubmit);
            btnDelete = new Button(this);
            btnDelete = (Button)getLayoutInflater().inflate(R.layout.btn_delete_template, null);
            btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (deleteSurvey()) {
                        Intent i = new Intent(self, MainActivity.class);
                        startActivity(i);
                    }
                }
            });

            ll.addView(btnDelete);
			this.setContentView(sv);
		}
	}

	private void createQuestionView(QuestionObj obj) {
		TextView tvQuestionTitle = new TextView(this);
        tvQuestionTitle = (TextView)getLayoutInflater().inflate(R.layout.tv_name_template, null);
		tvQuestionTitle.setText(obj.get_question_title());
		tvQuestionTitle.setId(obj.get_question_id());
		ll.addView(tvQuestionTitle);
        View line = new View(this);
        line = (View)getLayoutInflater().inflate(R.layout.separator_template, null);
        ll.addView(line);
        List<AnswerObj> answerObjs = obj.get_answers_list();
        if ((obj.get_answers_list().get(0).get_object_name().equals(Constants.radio_p))){
            createRadioButton(answerObjs);
        } else {
            createCheckbox(answerObjs);
        }
	}

    private void createRadioButton(List<AnswerObj> answerObjs) {
        RadioButton[] rb = new RadioButton[answerObjs.size()];
        RadioGroup rg = new RadioGroup(this);
        rg.setId(100 + answerObjs.get(0).get_question_id());
        rg.setOrientation(RadioGroup.VERTICAL);
        try {
        for (AnswerObj item : answerObjs) {
            rb[item.get_answer_order()]  = new RadioButton(this);
            rb[item.get_answer_order()].setText(item.get_answer_text());
            rb[item.get_answer_order()].setId(item.get_answer_id());
            rb[item.get_answer_order()].setTag(item.get_question_id());
            rb[item.get_answer_order()].setChecked(item.is_is_checked());
            rg.addView(rb[item.get_answer_order()]);
            rb[item.get_answer_order()].setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String q_id = String.valueOf(v.getTag());
                    List<AnswerObj> tempAnsw = currentSurvey.get_questions_list().get(Integer.valueOf(q_id)).get_answers_list();
                    for (AnswerObj updAnswer : tempAnsw){
                        if (updAnswer.get_answer_id() == v.getId()) {
                            currentSurvey.get_questions_list().get(Integer.valueOf(q_id)).get_answers_list().get(updAnswer.get_answer_id()).set_is_checked(((RadioButton) v).isChecked());
                        } else {
                            currentSurvey.get_questions_list().get(Integer.valueOf(q_id)).get_answers_list().get(updAnswer.get_answer_id()).set_is_checked(false);
                        }
                    }
                    //currentSurvey.get_questions_list().get(Integer.valueOf(q_id)).get_answers_list().get(v.getId()).set_is_checked(((RadioButton) v).isChecked());
                }
            });
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ll.addView(rg);
    }
	private void createCheckbox(List<AnswerObj> answerObjs) {
        try {
            for (AnswerObj item : answerObjs) {
                CheckBox cb = new CheckBox(this);
                cb.setText(item.get_answer_text());
                cb.setId(item.get_answer_id());
                cb.setTag(item.get_question_id());
                cb.setChecked(item.is_is_checked());
                cb.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        String q_id = String.valueOf(v.getTag());
                        currentSurvey.get_questions_list().get(Integer.valueOf(q_id)).get_answers_list().get(v.getId()).set_is_checked(((CheckBox) v).isChecked());
                    }
                });
                ll.addView(cb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

    private boolean saveResults() {
        boolean res = false;
        try {
            if (sManager == null) {
                sManager = new SurveyManager(self);
            }
            for (int i = 0; i < Constants.MAX_ATTEMPTS; i++)
            if (sManager.updateSurveyValues(currentSurvey)) {
                i = Constants.MAX_ATTEMPTS;
                res = true;
                // uncomment in case a survey has to be sent by submit
                //surveysToSend.add(currentSurvey);

//                ModelManager.getInstance(self).sendData(self, surveysToSend, "tempID", new ModelManagerListener() {
//                    @Override
//                    public void onSuccess(Object object) {
//                        JSONObject obj=(JSONObject)object;
//                        ServerResponse response = new ServerResponse();
//                        if (object != null && ((JSONObject) object).length()>0) {
//                            response.set_return_code(ParserUtility.getIntValue(obj,Constants.return_code_p));
//                            response.set_message(ParserUtility.getStringValue(obj, Constants.message_p));
//                        }
//                        if (response.get_return_code() >= 0){
//                            for (SurveyObj item : surveysToSend){
//                                item.set_is_sent(true);
//                                sManager.updateSentStatus(item);
//                            }
//                        }
//                    }
//                    public void onError(String message) {
//                        // TODO Auto-generated method stub
//                        //DialogUtil.alert(self, message);
//                    }
//                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private boolean deleteSurvey() {
        boolean res = false;
        try {
            if (sManager == null) {
                sManager = new SurveyManager(self);
            }
            sManager.deleteSurvey(currentSurvey);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
